const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const {createUser, getUserInfo,updateById} = require('../service/user.service')
const {userRegisterError} = require('../constant/err.type')
const {JWT_SECRET} = require('../config/config.default')
class UserController{
    async register(ctx,next){
        // 1.获取数据
        // console.log(ctx.request.body)
        const {user_name,password} = ctx.request.body

        // 合法性
        
        try {
            // console.log(aa);
            // 2.操作数据库
            const res = await createUser(user_name,password)
    
            // 3.返回结果
            ctx.body = {
                code: 0,
                message: '用户注册成功',
                result: {
                    id: res.id,
                    user_name: res.user_name,
                },
            }
        } catch (error) {
            ctx.app.emit('error',userRegisterError,ctx)
            return
        }
        
    }
    async login(ctx,next){
        const {user_name} = ctx.request.body
        // 获取用户信息(在token的payload中，记录id，user_name,is_admin)
        try {
            //从返回结果对象中，剔除password属性，将剩下的属性放到res新的对象里
            const {password,...res} = await getUserInfo({user_name})
            const data = {
                code:0,
                message:'用户登录成功',
                result:{
                    token:jwt.sign(res,JWT_SECRET,{ expiresIn:'1d' })
                }
            }
            ctx.body = data
            // console.log(ctx.body);
            await next()
        } catch (error) {
            console.error('用户登录失败',error)
        }


    }

    async updatePassword(ctx,next){
        //获取需改账号的id
        const id = ctx.state.user.id
        const password = ctx.request.body.password

        const res = await updateById({id,password})
        console.log(res);
        if(res){
            ctx.body={
                code:0,
                message:'修改密码成功',
                result:''
            }
            console.log('001');
        }else{
            ctx.body={
                code:'10007',
                message:'修改密码失败',
                result:""
            }
        }

        await next()

    }
}

module.exports = new UserController()